import { createStore, Store, useStore as useVuexStore } from 'vuex'
import { IRootState, IStoreType } from './types'
import loginModule from './login/login'
import systemModule from './main/system/system'
import dashboardModule from './main/analysis/dashboard'
import { getPageListData } from '@/service/main/system/system'

const store = createStore<IRootState>({
  state() {
    return {
      name: '123',
      age: 18,
      allDepartment: [],
      allRole: [],
      allMenu: []
    }
  },
  mutations: {
    changeAllDepartment(state, alld: any) {
      state.allDepartment = alld
    },
    changeAllRole(state, allr: any) {
      state.allRole = allr
    },
    changeAllMenu(state, allm: any) {
      state.allMenu = allm
    }
  },
  actions: {
    async getInitDataAction({ commit }) {
      // 请求部门和角色的数据
      const departmentResult = await getPageListData('/department/list', {
        offset: 0,
        size: 100
      })
      // * es6起别名: {list: xxx}
      const { list: departmentlist } = departmentResult.data
      commit('changeAllDepartment', departmentlist)
      const roleResult = await getPageListData('/role/list', {
        offset: 0,
        size: 100
      })
      const { list: rolelist } = roleResult.data
      commit('changeAllRole', rolelist)

      const menuResult = await getPageListData('/menu/list', {})
      const { list: menuList } = menuResult.data
      commit('changeAllMenu', menuList)
    }
  },
  modules: {
    login: loginModule,
    system: systemModule,
    dashboard: dashboardModule
  }
})
// 对vuex的state进行初始化
export function initStore() {
  store.dispatch('login/initStoreAction')
  // store.dispatch('getInitDataAction') // 必须拿到token才能请求
}
// 封装函数对vuex的module类型的使用
// 先拿到vuex的Store类型,再传入module合并的类型
// 替代默认的 useStore
export function useStore(): Store<IStoreType> {
  return useVuexStore() // 重名(as的使用),还是返回useSotore()
}

export default store
